package cn.pping.mq;

import cn.pping.domain.CourseOrder;
import cn.pping.dto.Order2PayOrderParamDto;
import cn.pping.service.ICourseOrderService;
import cn.pping.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;

import java.nio.charset.StandardCharsets;

@RocketMQTransactionListener(txProducerGroup = "TxOrderGroupListener")
public class TxOrderMqListener implements RocketMQLocalTransactionListener {
    /**
    * @Title: executeLocalTransaction
    * @Description: 执行本地事务
    * @Author: Pan
    * @Version: 1.0
    * @Date:  2022/9/18 23:56
    * @Parameters: [message, o]
    * @Return org.apache.rocketmq.spring.core.RocketMQLocalTransactionState
    */

    @Autowired
    private ICourseOrderService courseOrderService;
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            AssertUtil.isNotNull(o,"订单数据为空，保存订单失败！！");
            CourseOrder courseOrder = (CourseOrder) o;
            courseOrderService.saveOrderAndItems(courseOrder);
            return RocketMQLocalTransactionState.COMMIT;//执行本地事务成功
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;//本地事务执行失败，回滚
        }
    }

    /**
    * @Title: checkLocalTransaction
    * @Description: 检查本地事务
    * @Author: Pan
    * @Version: 1.0
    * @Date:  2022/9/18 23:56
    * @Parameters: [message]
    * @Return org.apache.rocketmq.spring.core.RocketMQLocalTransactionState
    */

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        // 需要持久化
        try {
            byte[] bytes = (byte[]) message.getPayload();
            String s = new String(bytes, StandardCharsets.UTF_8);
            Order2PayOrderParamDto order2PayOrderParamDto = JSON.parseObject(s, Order2PayOrderParamDto.class);
            CourseOrder courseOrder = courseOrderService.selectByOrderNo(order2PayOrderParamDto.getOrderNo());
            if(courseOrder != null){
                return RocketMQLocalTransactionState.COMMIT;//说明执行本地事务已经是成功了的
            }else{
                return RocketMQLocalTransactionState.ROLLBACK;//说明执行本地事务没有执行成功
            }
        }catch (Exception e){
            e.printStackTrace();
            // 记录各种失败日志（消息内容--表），各种通知运维人员，各种通知开发人员【ELK--钉钉-短信-邮件】  由人工接入处理
            return RocketMQLocalTransactionState.UNKNOWN; //我也不知道成功没有
        }

    }
}
